<?php
class Product_Service_Receiving
{
	public static $statusText = array(
		"0" => "已删除",
		"1" => "未收货",
		"2" => "收货中",
		"3" => "已收货",
		"4" => "异常",
	);
	public static $packagedText = array(
		"0" => "否",
		"1" => "是",
	);
	public static $orderTypeText = array(
		'0'=>'',
		"1" => "标准",
		"2" => "订单退货",
		"3" => "指定产品退货",
	);
	
	public function __construct(){
		
	}
	
	public static function getInstance(){
		return new Product_Service_Receiving();
	}

	public static function getByReceivingCode($code)
	{ 
		$obj=new Product_Model_Receiving();
		$rows=$obj->getByReceivingCode($code);
		if(!empty($rows)){
			$rows=$rows->toArray();
		}
		return $rows;
	}
	
	public static function getByCondition($condition=array(),$type='*',$page="", $pageSize="",$orderBy='')
	{ 	
		$obj=new Product_Model_Receiving();
		$rows= $obj->getByCondition($condition,$type, $page,$pageSize, $orderBy);	
		$itemModel = new Product_Model_ReceivingItem();
		if(is_array($rows)){
			foreach($rows as $key=>$row){
				$rows[$key]['orderTypeText'] = self::$orderTypeText[$row['order_type']];
				$rows[$key]["statusText"] = self::$statusText[$row['status']];
				if($itemModel->getUnNormal($row['receiving_code']) > 0){
					$rows[$key]['unNormal'] = "是";
				}else{
					$rows[$key]['unNormal'] = "否";
				}
			}
		}
		return $rows;
	}
	
	public static function getReturnsByCondition($condition=array(),$type='*',$page="", $pageSize="",$orderBy=array())
	{ 	
		$obj=new Product_Model_Receiving();
		$rows= $obj->getReturnsByCondition($condition,$type, $page,$pageSize,$orderBy);	
		$itemModel = new Product_Model_ReceivingItem();
		if(is_array($rows)){
			foreach($rows as $key=>$row){
				$rows[$key]['orderTypeText'] = self::$orderTypeText[$row['order_type']];
				$rows[$key]["statusText"] = self::$statusText[$row['status']];
				if($itemModel->getUnNormal($row['receiving_code']) > 0){
					$rows[$key]['unNormal'] = "是";
				}else{
					$rows[$key]['unNormal'] = "否";
				}
			}
		}
		return $rows;
	}
	
	
	public static function getItems($receivingCode){
		$obj=new Product_Model_ReceivingItem();
		$pspobj= new Product_Service_Product();
		$rows= $obj->getByCondition(array("receiving_code" => $receivingCode));
		if(is_array($rows)){
			foreach($rows as $key=>$row){
				$rows[$key]["statusText"] = self::$statusText[$row['status']];
				$rows[$key]["packagedText"] = self::$packagedText[$row['packaged']];
				$rows[$key]["product"] = $pspobj->getProductInfo($row['product_id']);
			}
		}
		return $rows;
	}
	
	public static function getPicture($productId){
		$attach = new Product_Model_Attached();
		$picture = $attach->getViewPicture($productId);
		$pspobj= new Product_Service_Product();
		$product = $pspobj->getProductInfo($productId);
		$result = false;
		if($picture instanceof Zend_Db_Table_Row){
			$picture = $picture->toArray();
			if($picture['pa_file_type'] == "img"){
				$result = "../../front/data/images/".$product['customer_id']."/".$product['product_id']."/".$picture['pa_path'];
			}else{
				$result = $picture['pa_path'];
			}
		}
		return $result;
	}
	
	public static function getByReceivingItemCondition($condition=array(),$type='*',$page="", $pageSize="")
	{ 
		$obj=new Product_Model_ReceivingItem();
		$pspobj= new Product_Service_Product();
		$rows= $obj->getByCondition($condition,$type, $page,$pageSize);	
		if(is_array($rows)){
			foreach($rows as $key=>$row){
				$Receiving=self::getByReceivingCode($row['receiving_code']);
				$rows[$key]["statusText"] = self::$statusText[$row['status']];
				$rows[$key]["customer_id"] = $Receiving['customer_id'];
				$rows[$key]["order_type"] = $Receiving['order_type'];
				$rows[$key]["category"] = $pspobj->getProductCategory($row['product_id']);
			}
		}
		return $rows;
	}

	public static function getItemByProductId($productId){
		$obj=new Product_Model_ReceivingItem();
		$item = $obj->getByProductId($productId);
		if($item instanceof Zend_Db_Table_row){
			$item = $item->toArray();
			$pspobj= new Product_Service_Product();
			$item['product'] = $pspobj->getProductInfo($productId);
			return $item;
		}
		return false;
	}
	
	public static function getItemByItemId($itemId){
		$obj=new Product_Model_ReceivingItem();
		$item = $obj->getByReceivingId($itemId);
		if($item instanceof Zend_Db_Table_row){
			$item = $item->toArray();
			$pspobj= new Product_Service_Product();
			$item['product'] = $pspobj->getProductInfo($item['product_id']);
			return $item;
		}
		return false;
	}
	
	
	public static function receiveAdd($row){
		$item = self::getItemByItemId($row['ri_id']);
		if($item){
			if($item['status'] == 1){
				return array(
						"code" => 0,
						"message" => "该产品已经收货,无法再次操作",
					);
			}
			if(!is_numeric($row['weight'])){
				return array(
						"code" => 1,
						"message" => "重量必须是数字",
					);
			}
			if(!preg_match("/^\d+$/",$row['received_qty'])){
				return array(
						"code" => 2,
						"message" => "数量必须是正整数",
					);
			}
//			if(!preg_match("/^\d+$/",$row['non_labeled_qty'])){
//				return array(
//						"code" => 3,
//						"message" => "无label数量必须是正整数",
//					);
//			}
			if(abs($row['weight'] - $item['product']['product_weight']) > 0.02 && $row['remark'] == ""){
				return array(
						"code" => 4,
						"message" => "重量差异超过0.02Kg",
					);
			}
			if($row['received_qty'] != $item['order_qty']  && $row['remark'] == ""){
				return array(
						"code" => 5,
						"message" => "数量出现误差,请填写异常信息",
					);
			}
			if($row['non_labeled_qty'] > $row['received_qty']){
				return array(
						"code" => 6,
						"message" => "无label数量不能大于实收数量",
					);
			}
			$productService = new Product_Service_Product();
			$db = $productService->getAdapter()->beginTransaction();
			try{

				//检测改ASN是否已经全部收货
				// $receiving = self::getByReceivingCode($item['receiving_code']);
				$receivingItems = self::getItems($item['receiving_code']);
				$unReceived = 0;
				$lineNo = 0;//收货编号
				foreach($receivingItems as $key => $value){
					if($value['status'] == 0) $unReceived++;
					if($value['line_no'] > $lineNo) $lineNo = $value['line_no'];
				}
				$lineNo++;
				if($unReceived == 1){//更新状态
					self::changeStatus($item['receiving_code'],3);
				}

				$obj=new Product_Model_ReceivingItem();
				$row['status'] = 1;
				$row['line_no'] = $lineNo;
				$rows = $obj->update($row,$row['ri_id']);
				if(!$rows){
					$db->rollback();
					return array(
						"code" => 8,
						"message" => "更新收货信息失败!",
					);
				}
				$db->commit();
				return true;
			}catch(Exception $e){
				$db->rollback();
			}
		}
		return false;
	}
	
	/*数据验证
	*return array('ask'=>0,'error'=>'错误信息!');
	*return array('ask'=>1,'result'=>'格式化后的数据');
	*/
	private function ReceiveValidate($option=array()){
		if(!isset($option['receiveQty']) || $option['receiveQty']=='' ){
			return array('ask'=>0,'error'=>'数据出错!');
		}
		$rows=array(
			'order_qty'=>$option['orderQty'],
			'received_qty'=>$option['receiveQty'],
			'non_labeled_qty'=>$option['nonLabelQty'],
			'product_sku'=>$option['sku'],
			'remark'=>$option['remark'],
			'weight'=>$option['weight'],
			'param_non_labeled_qty'=>$option['nonLabelQty'],//用于扣费
			'param_received_qty'=>$option['receiveQty'],//用于QC
		);

		if(isset($option['isPacket'])){
			$rows['packaged']=$option['isPacket'];
		}
		if(isset($option['isBatch'])){
			$rows['isbatch']=$option['isBatch'];
		}
		//数据验证
		foreach($rows['received_qty'] as $key => $val){
			$item = self::getItemByItemId($key);
			if(empty($item)){
				return array('ask'=>0,'error'=>'没有找到item数据!');
			}

			if($item['status'] == 2){
				return array(
						"ask" => 0,
						"error" => "SKU: ".$rows['product_sku'][$key]." 已经完成收货,无法再次操作",
					);
			}
			
			if(!preg_match("/^\d+$/",$val)){
				return array(
						"ask" => 0,
						"error" =>  "SKU: ".$rows['product_sku'][$key]." 收货数量必须是正整数",
					);
			}
			if($rows['received_qty'][$key] != $rows['order_qty'][$key] && (!isset($rows['isbatch'][$key])) && $rows['remark'][$key] == ""){
				return array(
						"ask" => 0,
						"error" => "SKU: ".$rows['product_sku'][$key]." 数量出现误差,请填写异常信息",
					);
			}
			if($rows['non_labeled_qty'][$key] > $rows['received_qty'][$key]){
				return array(
						"ask" => 0,
						"error" => "SKU: ".$rows['product_sku'][$key]." 无label数量不能大于实收数量",
					);
			}
			if($rows['received_qty'][$key] == $rows['order_qty'][$key] && isset($rows['isbatch'][$key]) ){
				return array(
						"ask" => 0,
						"error" => "SKU: ".$rows['product_sku'][$key]." 实收数量等于应收数量,不存在分批收货!",
					);
			}
			if(abs($rows['weight'][$key] - $item['product']['product_weight']) > 0.02 && $rows['remark'][$key] == ""){
				return array(
						"ask" => 0,
						"error" => "SKU: ".$rows['product_sku'][$key]." 重量差异超过0.02Kg,请填写异常信息!",
					);
			}
			//处理分批收货第二次提交的数据
			if($item['status'] == 1 ){
				//实际收货数量加上之前已收货数量
				$rows['received_qty'][$key]=$rows['received_qty'][$key]+$item['received_qty'];
				$rows['non_labeled_qty'][$key]=$rows['non_labeled_qty'][$key]+$item['non_labeled_qty'];
				if($rows['received_qty'][$key] == $item['order_qty'] && isset($rows['isbatch'][$key]) ){
					return array(
							"ask" => 0,
							"error" => "SKU: ".$rows['product_sku'][$key]." 实收数量等于应收数量,不存在分批收货!",
						);
				}
			}
			
			$rows['ri_id'][$key]=$key;
			//如是是分批收货。状态是收货中
			if(isset($rows['isbatch'][$key])){
				$rows['status'][$key]=1;
			}else{
				$rows['status'][$key]=2;
			}
			//是否带包装
			if(isset($rows['packaged'][$key])){
				$rows['packaged'][$key]=1;
			}else{
				$rows['packaged'][$key]=0;
			}
			$rows['is_qc'][$key]=$item['is_qc'];
			$rows['receiving_code']=$item['receiving_code'];
			$rows['product_id'][$key]=$item['product_id'];
			
		}
		return array('ask'=>1,'result'=>$rows);
	}
	
	/*数据提交
	*param array(
		'receiving_code'=>
		'ri_id'=>
		'received_qty'=>
		'non_labeled_qty'=>
		'packaged'=>
		'weight'=>
		'remark'=>
		'status'=> 判断是否分批收货。分批收货->1(收货中),2->完成收货
	)
	return true false;
	*/
	private function procAddReceive($options=array()){
		$receivingItems = self::getItems($options['receiving_code']);
		$receiving_code = $options['receiving_code'];
		$lineNo = 0;//收货编号
		$product_weight = 0;	
		foreach($receivingItems as $key => $value){
			if($value['line_no'] > $lineNo) $lineNo = $value['line_no'];
			if($options['ri_id'] == $value['ri_id']){
				$product_weight = $value['product']['product_weight'];	//获取产品重量
			}
		}
		$lineNo++;
		
		$obj=new Product_Model_ReceivingItem();
		$ri_id=$options['ri_id'];
		unset($options['receiving_code']);
		unset($options['ri_id']);
		$options['line_no'] = $lineNo;
		//$options['weight'] = $product_weight;// 收货时已填写
		
		$rows = $obj->update($options,$ri_id);
		
		// 更新收货人 和 收货时间
		$objReceiving = new Product_Model_Receiving();
		$session = new Zend_Session_Namespace('userAuth');
		$cond = array('modified_by'=>$session->userID,'modified'=>date('Y-m-d H:i:s'));
		$res = $objReceiving->update($cond,$receiving_code);
		
		if(!$rows ){
			return false;
		}
		return true;
	}
	
	/**
	*批量收货
	*@return array('ask'=>0,'error'=>'错误信息!');
	*/
	public static function procReceiveTransaction($postoption=array()){
		//数据验证,格式化数据
		$result=self::ReceiveValidate($postoption);
		if(isset($result['ask']) && $result['ask']==1 ){
			$option=$result['result']; //使用格式化后的数据
		}else{
			return $result; //返回错误信息
		}

		$date=date("Y-m-d:H:i:s");
		$WMProducts = new Warehouse_Model_Products();
		$plan = new Plan_Service_Plan();
		$dbAdapter = $WMProducts->getAdapter();
		$dbAdapter->beginTransaction(); 
		try{
			$non_labeled_qty_count=0;//本次检查到无label总数量
			$is_qc_count=0;
			foreach($option['received_qty'] as $key => $val){
			
				$updateRow=array(
					'receiving_code'=>$option['receiving_code'],
					'ri_id'=>$option['ri_id'][$key],
					'received_qty'=>$option['received_qty'][$key],
					'non_labeled_qty'=>$option['non_labeled_qty'][$key],
					'packaged'=>$option['packaged'][$key],
					'weight'=>$option['weight'][$key],
					'remark'=>$option['remark'][$key],
					'status'=>$option['status'][$key],
				);
			
				if(!self::procAddReceive($updateRow)){
					$dbAdapter->rollback();
					return array('ask'=>0,'error'=>'更新item数据错误!');
				}
				//统计总数
				$non_labeled_qty_count+=$option['param_non_labeled_qty'][$key];
			}
			$receiving = self::getByReceivingCode($option['receiving_code']);
			$customerId = $receiving['customer_id'];
			$curr_status = $receiving['status'];
			//更新ASN状态
			$ASN_status=3;//已收货
			$receivingItems = self::getItems($option['receiving_code']);
			foreach($receivingItems as $key => $value){
				if($value['status']==1) $ASN_status=2;
			}
			//不是相同状态才更新
			if($ASN_status != $curr_status){
				$receivingModel = new Product_Model_Receiving();
				if(!$receivingModel->update(array("status" => $ASN_status),$option['receiving_code'])){
					$dbAdapter->rollback();
					return array(
						"ask" => 0,
						"error" => "ASN状态更新失败!",
					);
				}
			}
			
			$dbAdapter->commit();
			$result['ask']=1;
			$result['result']="操作成功!";
			if($is_qc_count>0){
				$result['result']="操作成功!"."创建QC：".$qco_code;
			}
			return $result;
		}catch(Exception $e){
			$dbAdapter->rollback();
			return array(
				"ask" => 0,
				"error" => "内部错误!",
			);
		}
	}
	
	public static function confirmProduct($productId){
		$pspobj= new Product_Service_Product();
		$product = $pspobj->getProductInfo($productId);
		if(is_array($product) && !empty($product)){
			if($pspobj->update(array("product_warehouse_status" => 1),$productId)){
				return true;
			}
		}
		return false;
	}
	
	public static function editProduct($row){
		if(!is_numeric($row['weight']) || !is_numeric($row['declared'])||$row['weight'] <=0){
            return array(
                "code" => 0,
                "message" => "重量、申报价值必须是大于0的数字");
        }
        if(!is_numeric($row['product_length']) || !is_numeric($row['product_width']) || !is_numeric($row['product_height']) || $row['product_length'] <=0 || $row['product_width'] <=0 || $row['product_height'] <=0){
            return array(
                "code" => 0,
                "message" => "长、宽、高,必须是大于0的数字");
        }
		$pspobj= new Product_Service_Product();
		$product = $pspobj->getProductInfo($row['productId']);
		if(is_array($product) && !empty($product)){
			$db = $pspobj->getAdapter();
			$db->beginTransaction();
			$productRow = array(
				"product_id" => $row['productId'],
				"product_weight" => $row['weight'],
				"product_declared_value" => $row['declared'],
				"product_warehouse_status" => 1,
                "product_length" => $row['product_length'],
                "product_width" => $row['product_width'],
                "product_height" => $row['product_height'],
			);
			try{
				if($pspobj->update($productRow,$row['productId'])){
					//更新品类
					$optionModel = new Product_Model_ProductOptions();
					$option = $optionModel->getByName("Category");
					$povModel = new Product_Model_ProductOptionValue();
					$povModel->update(array("poc_id" => $row['category']),$row['productId'],$option['po_id']);
					//更新包装
					$ppmModel = new Product_Model_PackageMap();
					$ppm = $ppmModel->getByProductIdAndWarehouseId($row['productId'],$row['warehouseId']);
					if($ppm instanceof Zend_Db_Table_Row){
						$ppm = $ppm->toArray();
						$ppmModel->update(array("package_id" => $row['packet']),$ppm['ppm_id']);
					}else{
						$ppmModel->add(array("package_id" => $row['packet'],"product_id"=>$row['productId'],"warehouse_id"=>$row['warehouseId']));
					}
				}
				$db->commit();
				return true;
			}catch(Exception $e){
				$db->rollback();
				return false;
			}
			
		}
		return false;
	}
	
	public static function changeStatus($receivingCode,$status){
		$receivingModel = new Product_Model_Receiving();
		$receiving = self::getByReceivingCode($receivingCode);
		if($status==2 && $receiving['status'] > 2){//只有第一次打印改变状态
			$status = $receiving['status'];
		}
		return $receivingModel->update(array("status" => $status),$receivingCode);
	}
	
	
	public function getByValue($value,$field='receiving_id'){
		$Obj = new Product_Model_Receiving();
		return $Obj->getByValue($value,$field);	
	}
	
	/**
	 * 获取当天最后一个 退货code
	 */
	public function getCurdateLastReturnCode($customer_id){
		$Obj = new Product_Model_Receiving();
		$row = $Obj->getCurdateLastReturnCode($customer_id);
		return $row;		
	}
	
	
}